package de.freudenreichdesign.webshop.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;

@Entity
@Table(name="USER")
public class User implements UserDetails{

	private static final long serialVersionUID = 5374483864699868299L;
	private Customer customer;
    private String userName;
    private String password;
    private GrantedAuthority[] authorities;
	
    @ManyToMany
	@Override
	public Collection<GrantedAuthority> getAuthorities() {
		List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(); 
		for (int i = 0; i < authorities.length; i++) {
			result.add(authorities[i]);
		}
		return result;
	}

    @Column(name="PASSWORD")
	@Override
	public String getPassword() {
		return password;
	}

    @Column(name="USERNAME")
	@Override
	public String getUsername() {
		return userName;
	}

    @Transient
	@Override
	public boolean isAccountNonExpired() {
		return false;
	}

    @Transient
	@Override
	public boolean isAccountNonLocked() {
		return false;
	}

    @Transient
	@Override
	public boolean isCredentialsNonExpired() {
		return false;
	}

    @Transient
	@Override
	public boolean isEnabled() {
		return false;
	}

	public void setCustomerAuthorities(List<String> roles) {
        List<GrantedAuthority> listOfAuthorities = new ArrayList<GrantedAuthority>();
        for (String role : roles) {
            listOfAuthorities.add(new GrantedAuthorityImpl(role));
        }
        authorities = (GrantedAuthority[])listOfAuthorities.toArray();
    }
	
	public void setCustomer(Customer customer) {
		this.customer = customer;
	}

	@OneToOne
	@JoinColumn(name="CUSTOMER_ID")
	public Customer getCustomer() {
		return customer;
	}

}
